package com.zxq.common.utils;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import org.apache.commons.lang3.StringUtils;

public class PhoneNoUtil {

    private static final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();

    /**
     * 判断手机号是否合法
     * @param phoneNumber
     * @return
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (StringUtils.isBlank(phoneNumber)) {
            return false;
        }

        String regionCode = "CN";
        try {
            Phonenumber.PhoneNumber number = phoneNumberUtil.parse(phoneNumber, regionCode);
            return phoneNumberUtil.isValidNumber(number);
        } catch (NumberParseException e) {
            return false;
        }
    }

    /**
     * 获取手机号后四位
     * @param phoneNumber
     * @return
     */
    public static String getLastFourDigits(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() < 4) {
            throw new IllegalArgumentException("手机号格式不正确，必须至少包含4位数字");
        }
        return phoneNumber.substring(phoneNumber.length() - 4);
    }

    /**
     * 手机号中间四位替换为*
     * @param phoneNumber
     * @return
     */
    public static String maskMiddleFourDigits(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.length() != 11) {
            throw new IllegalArgumentException("手机号格式不正确，必须为11位数字");
        }
        String prefix = phoneNumber.substring(0, 3);  // 获取前3位
        String suffix = phoneNumber.substring(7);    // 获取后4位
        return prefix + "****" + suffix;             // 拼接替换后的手机号
    }

}
